import {GetList, GetReworkDetail, ProcessRework} from '@/api/rework'
import React, {useContext, useEffect, useReducer, useState} from 'react'
import {Button, Card, Col, DatePicker, Drawer, Form, Input, notification, Row, Select, Space, Table} from 'antd'
import {useAntdTable, useRequest} from 'ahooks'
import {getQcReasonDetailList, getQcReasonList, getQcSolutionList} from '@/api/maintain'
import {ERR_OK} from '@/utils/commons'
import PhotoListSelect from '@/commonComp/photoListSelect'
import {rpd} from '@/views/productManagement/components/common'
import {exportExData} from "@/commonComp/export";

const {RangePicker} = DatePicker
const {Option} = Select

const timeParamFormat = (m) => m ? m.format('YYYY-MM-DD') : ''
const tpf = timeParamFormat

const getTableData = (
  {current, pageSize},
  formData
) => {
  console.log('formData => %o', formData)
  const {dataRange: [s, e] = [], keyName = '', ...restP} = formData
  return GetList({
    ...{...restP, StartTime: s|> tpf, EndTime: e|> tpf, KeyName: keyName},
    ...{Page: current, PageSize: pageSize}
    // ...{ Status: -1 }
  }).then(({Result, Code}) => {
    const {TotalNum, Items, CurrentPage} = Result
    return {
      total: TotalNum,
      list: Items
    }
  })
}

const columns = [
  // {dataIndex:'ReworkID',title: 15},
  {dataIndex: 'ShopName', title: '商户名'},
  {dataIndex: 'OrderProductName', title: '产品名'},
  {dataIndex: 'OrderProcuctCode', title: '产品编号'},
  // {dataIndex:'OrderProductID',title: 67101},
  {dataIndex: 'OrderProductPartCode', title: '组件号'},
  // {dataIndex:'OrderProductPartID',title: 67153},
  {dataIndex: 'FromTechName', title: '返工流程'},
  // {dataIndex:'FromTechID',title: 0},
  {dataIndex: 'ToTechName', title: '返工至'},
  // {dataIndex:'ToTechId',title: 0},
  {dataIndex: 'CommitUserName', title: '返工人'},
  {dataIndex: 'OrderTime', title: '订单时间'},
  {dataIndex: 'ReworkDate', title: '返工时间'},
  {dataIndex: 'ProcessDate', title: '处理时间'},
  {dataIndex: 'ProcessMam', title: '处理人'},
  {dataIndex: 'Reason', title: '返工原因'},
  // {dataIndex:'ReasonId',title: 1},
  {dataIndex: 'Solution', title: '解决方式'},
  {dataIndex: 'FileNum', title: '返工照片数量'}
  // {dataIndex:'ReworkFiles',title: null},
  // {dataIndex:'SolutionID',title: 0},
  // {dataIndex:'ReasonDetailID',title: 1},
]

const defState = {
  reworkDrawerVis: false,
  reworkProcessData: {},  //  当前点击的返工组件
  photoDetails: {} //  组件的照片信息
}

const ctx = React.createContext({
  state: defState, dispatch: () => {
  }
})

const reducer = (state, action) => {
  const {type, ...payloads} = action
  const {visible, row, details} = payloads
  const conditions = {
    setReworkDrawerVis: () => ({...state, reworkDrawerVis: visible}),
    setReworkProcessData: () => ({...state, reworkProcessData: row}),
    setPhotoDetails: () => ({...state, photoDetails: details})
  }
  const c = conditions[type]
  return c ? c() : state
}

const ProcessReworkDrawer = () => {

  const {state, dispatch} = useContext(ctx)
  const {reworkDrawerVis, reworkProcessData, photoDetails} = state
  const [form] = Form.useForm()

  const [qReasonOpts, setQReasonOpts] = useState([])  //  不良原因大类
  const [qReasonDetailOpts, setQReasonDetailOpts] = useState([])  //  不良原因细类
  const [qSolutionOpts, setQSolutionOpts] = useState([])   //  解决办法

  const [checkedPhotos, setCheckedPhotos] = useState([])

  const {OrderTechRoutes = [], OrderFiles = []} = photoDetails

  useEffect(() => {
    (async () => {
      Array.of([setQReasonOpts, getQcReasonList],
        [setQReasonDetailOpts, getQcReasonDetailList],
        [setQSolutionOpts, getQcSolutionList]).map(async ([set, req]) => {
        try {
          const {Result, Code} = await req()
          if (Code === ERR_OK) set(Result)
        } catch (e) {
          console.log(e)
        }
      })
    })()
  }, [])

  const onClose = () => {
    dispatch({type: 'setReworkDrawerVis', visible: false})
  }

  const onSubmit = async () => {
    try {
      await form.validateFields()
      form.submit()
      dispatch({type: 'setReworkDrawerVis', visible: false})
    } catch (e) {
      console.log(e)
    }
  }

  const {run} = useRequest(ProcessRework, {
    manual: true, onSuccess: () => {
      notification.success({message: '提交返工处理成功.'})
    }
  })

  const onFinish = async (datums) => {
    const {ReworkID} = reworkProcessData
    await run(Array.of({
      ...datums, ReworkID,
      ReworkFiles: checkedPhotos.map(OrderfileId => ({OrderfileId}))
    }))
  }

  const {ToTechId, ReasonDetailID, SolutionID, ReasonId} = state.reworkProcessData

  function transferZeroToPlainStr(obj) {
    return Object.entries(obj).reduce((acc, [k, v]) => v === 0 ? acc : {...acc, [k]: v}, {})
  }

  const t = transferZeroToPlainStr({ToTechId, ReasonDetailID, SolutionID, ReasonId})
  console.log('t ttttttttt  state 3333333 => %o', t)

  return <Drawer
    title="处理返工"
    width={900}
    onClose={onClose}
    visible={reworkDrawerVis}
    bodyStyle={{paddingBottom: 80}}
    footer={
      <div
        style={{
          textAlign: 'right'
        }}
      >
        <Button onClick={onClose} style={{marginRight: 8}}>
          取消
        </Button>
        <Button onClick={onSubmit} type="primary">
          提交
        </Button>
      </div>
    }
  >

    <Form initialValues={t} onFinish={onFinish} form={form} layout="vertical">
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="ReasonId"
            label="不良原因大类"
            rules={[{required: true, message: 'Please select an ReasonId'}]}
          >
            <Select>
              {qReasonOpts.map(({ReasonID, Description}) => {
                return <Option key={ReasonID} value={ReasonID}>{Description}</Option>
              })}
            </Select>
          </Form.Item>
        </Col>

        <Col span={12}>
          <Form.Item
            name="SolutionID"
            label="解决方式"
            rules={[{required: true, message: 'Please select an SolutionID'}]}
          >
            <Select>
              {qSolutionOpts.map(({SolutionID, Description}) => {
                return <Option key={SolutionID} value={SolutionID}>{Description}</Option>
              })}
            </Select>
          </Form.Item>
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="ReasonDetailID"
            label="不良原因细类"
            rules={[{required: true, message: 'Please select an ReasonDetailID'}]}
          >
            <Select>
              {qReasonDetailOpts.map(({ReasonDetailID, Description}) => {
                return <Option key={ReasonDetailID} value={ReasonDetailID}>{Description}</Option>
              })}
            </Select>
          </Form.Item>
        </Col>

        <Col span={12}>
          <Form.Item
            name="ToTechId"
            label="返回工序"
            rules={[{required: true, message: 'Please select an TechName'}]}
          >
            <Select>
              {OrderTechRoutes.map(({TechId, TechName}) => {
                return <Option key={TechId} value={TechId}>{TechName}</Option>
              })}
            </Select>
          </Form.Item>
        </Col>
      </Row>
    </Form>

    <PhotoListSelect {...{
      photos: OrderFiles,
      checkedPhotos: checkedPhotos,
      onChangeCheckPhotos: ids => setCheckedPhotos(ids),
      imgSrcProp: 'CompressPath',
      renderCardDetail: rpd,
      pid: 'OrderFileId'
    }}/>
  </Drawer>
}
const {Meta} = Card

const InsideReworkProcess = () => {
  const [form] = Form.useForm()

  const antTable = useAntdTable(getTableData, {
    defaultPageSize: 10, form, debounceInterval: 500
  })

  const [state, dispatch] = useReducer(reducer, defState)

  console.log('antTable => %o ', antTable)
  const {tableProps, search, loading} = antTable
  const {type, changeType, submit, reset} = search

  const {run} = useRequest(GetReworkDetail, {
    onSuccess: ({Result, Code}, params) => {
      dispatch({type: 'setPhotoDetails', details: Result})
    },
    manual: true
  })

  const handleProcessRework = async ({row}) => {
    const {ReworkID} = row

    console.log('ReworkID   => ', ReworkID)
    Array.of(['setReworkDrawerVis', {visible: true}],
      ['setReworkProcessData', {row}]).forEach(([act, payload]) => {
      dispatch({type: act, ...payload})
    })
    await run({rworkId: ReworkID})  //  query details
  }

  const cols = [
    ...columns,
    {
      title: '操作',
      key: 'action',
      render: (text, row) => (
        <Space size="middle">
          <Button
            disabled={row.Status > 0}
            type="primary" onClick={_ => handleProcessRework({row})}>处理返工</Button>
        </Space>
      )
    }
  ]

  const es = [
    {label: '申请', value: 0},
    {label: '处理中', value: 1},
    {label: '处理完成', value: 2}
  ]
//   total: TotalNum,
//       list: Items
  const exportData = async () => {
    await exportExData(columns, (params) => getTableData({current: 1, pageSize: 999999999}, params)
      .then(({list, total}) => ({
        Code: ERR_OK,
        Message: '',
        Result: {Items: list},
        ErrorCode: 1
      })), form.getFieldsValue())
  }

  const searchForm = (
    <Form form={form} style={{display: 'flex', justifyContent: 'flex-end', alignItems: 'center'}}>
      <Space style={{marginRight: 20}}>
        <Form.Item name="keyName">
          <Input.Search onPressEnter={submit} placeholder={'请输入关键字搜索'} enterButton style={{width: 240}}
                        onChange={submit}/>
        </Form.Item>
        <Form.Item name="Status">
          <Select allowClear placeholder={'根据状态过滤'} style={{width: 170}} onChange={submit}>
            {es.map(({label, value}) => <Option value={value}>{label}</Option>)}
          </Select>
        </Form.Item>
        <Form.Item name="dataRange">
          <RangePicker onChange={submit}/>
        </Form.Item>

        <Form.Item>
          <Button onClick={exportData} type="primary">导出数据</Button>
        </Form.Item>

      </Space>
    </Form>)

  return (<div style={{margin: 10}}>
      <ctx.Provider value={{dispatch, state}}>
        {/*<Azure/>*/}
        <div style={{marginTop: 16}}>
          {searchForm}
        </div>
        <Table columns={cols} rowKey="ReworkID" {...tableProps} />
        <ProcessReworkDrawer/>
      </ctx.Provider>
    </div>
  )
}

export default InsideReworkProcess
